package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.dao.OrdersDao;
import com.itheima.domain.AddressBook;
import com.itheima.domain.OrderDetail;
import com.itheima.domain.Orders;
import com.itheima.domain.ShoppingCart;
import com.itheima.domain.User;
import com.itheima.dto.OrdersDto;
import com.itheima.service.AddressBookService;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import com.itheima.service.UserService;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao,Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 用户下单  添加订单信息
     *
     * @param orders
     * @return
     */

    @Override
    @Transactional   //开启事务
    public void submit(Orders orders) {

        //获取用户id
        Long currentId = BaseContext.getCurrentId();
        User user = userService.getById(currentId);  //当前用户对象

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        //当前用户在购物车可能存在多个菜品或套餐
        //SQL: select * from shopping_cart where user_id = ?
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            //用户购物车为空 抛出异常
            throw new CustomException("当前用户购物车为空，无法下单");
        }


        //获取地址簿信息  前端已发送地址簿主键ID -->可以明确当前用户具体的地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            //用户没有地址信息
            throw new CustomException("当前用户没有收货地址，无法下单");
        }


        //工具类  自动生成订单编号
        long orderId = IdWorker.getId();  //订单号


        //原子性计算累加
        AtomicInteger amount = new AtomicInteger();

        //组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> { //item 表示该用户购物车每条数据
            OrderDetail orderDetail = new OrderDetail();     //创建订单明细对象
            orderDetail.setOrderId(orderId);                 //设置订单表主键
            orderDetail.setNumber(item.getNumber());         //设置数量
            orderDetail.setDishFlavor(item.getDishFlavor()); //设置口味   可能为null
            orderDetail.setDishId(item.getDishId());         //设置菜品主键id
            orderDetail.setSetmealId(item.getSetmealId());   //设置套餐主键id
            orderDetail.setName(item.getName());             //菜品 或 套餐名称
            orderDetail.setImage(item.getImage());           // 图片名称
            orderDetail.setAmount(item.getAmount());         // 单个金额
            // amount = 单件金额  *  数量
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单表插入数据, 一条数据
        orders.setId(orderId);                          //id
        orders.setNumber(String.valueOf(orderId));      //订单号
        orders.setStatus(2);                            //待送状态
        orders.setUserId(user.getId());                 //用户ID
        orders.setAddressBookId(addressBookId);         //地址ID
        orders.setOrderTime(LocalDateTime.now());       //下单时间
        orders.setCheckoutTime(LocalDateTime.now());    //结账时间
        orders.setPayMethod(1);                         //支付方式
        orders.setAmount(new BigDecimal(amount.get())); //总金额
        orders.setRemark(orders.getRemark());           //前段传来备注
        orders.setPhone(addressBook.getPhone());        //地址簿上用户电话
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        orders.setConsignee(addressBook.getConsignee()); //地址簿上收货人

        //sql: INSERT INTO orders values(?,?,?,?,?,?,?,?,?,?,?,?)
        this.save(orders);


        //向订单明细表插入数据, 多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        //LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //lambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);  //user_id = id
        //SQL : delete from shopping_cart where user_id = ?
        shoppingCartService.remove(queryWrapper);

    }

    /**
     * 查询订单列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page list(int page, int pageSize) {

        //构建分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        //构建条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());  // user_id = id
        queryWrapper.orderByDesc(Orders::getOrderTime);                // ordertime asc 时间降序

        //SQL：select * from orders where user_id = ?
        this.page(pageInfo, queryWrapper);

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records"); // 对象拷贝

        List<Orders> records = pageInfo.getRecords();                    //订单集合
        List<OrdersDto> ordersDtoList = records.stream().map(item -> {   //每一个 item --> orders订单对象
            OrdersDto ordersDto = new OrdersDto();      //空对象
            BeanUtils.copyProperties(item, ordersDto);  //对象拷贝

            Long id = item.getId();    //每个订单对象 id
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, id);


            //SQL：select * from order_detail where order_id = ?
            List<OrderDetail> list = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(list);

            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);

        return ordersDtoPage;
    }


    /* *
     *  再来一单
     * @param ordersDto
     * */
    @Override
    public void again(Orders orders) {

        // 获取当前携带过来的 订单id
        Long id = orders.getId();
        System.out.println(BaseContext.getCurrentId());

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(Orders::getId, id);    // id = id

        //SQL： select * from orders where id = ?
       // Orders orders = this.getById(queryWrapper);   // 查询到订单对象
        Orders orders1 = this.getOne(queryWrapper);
        //判断
        if (orders1 != null) {
            //存在

            //构建条件构造器
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orders1.getId());

            // SQL： select * from order_detail where order_id = id
            List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);  //当前订单下具体订单明细集合

            //将信息重新添加进购物车
            List<ShoppingCart> shoppingCarts = orderDetails.stream().map(item -> {
                //创建购物车对象
                ShoppingCart shoppingCart = new ShoppingCart();

                shoppingCart.setName(item.getName());   //设置菜名或套餐名
                shoppingCart.setImage(item.getImage()); // 设置图片
                shoppingCart.setUserId(BaseContext.getCurrentId()); //设置当前user_id
                shoppingCart.setDishId(item.getDishId()); //设置菜品id
                shoppingCart.setSetmealId(item.getSetmealId()); //设置套餐id
                shoppingCart.setDishFlavor(item.getDishFlavor()); //设置口味
                shoppingCart.setNumber(1);  //默认份数
                shoppingCart.setAmount(item.getAmount()); //设置单价
                shoppingCart.setCreateTime(LocalDateTime.now());  //设置添加购物车时间

                return  shoppingCart;
            }).collect(Collectors.toList());

            // 添加进购物车
            shoppingCartService.saveBatch(shoppingCarts);
            //创建购物车对象
            //ShoppingCart shoppingCart = new ShoppingCart();
            //shoppingCart.setUserId(BaseContext.getCurrentId());

        } else {
            throw new CustomException("订单不存在，请重新下单！");
        }
    }
}